﻿using System;
using System.IO;
using System.Diagnostics;

namespace extractat3aswav
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args == null)
            {
                Console.WriteLine("Usage: extractat3aswav.exe filetoextractat3from.ext");
            }
            else
            {
                byte[] content = File.ReadAllBytes(args[0]);
                string contents = BitConverter.ToString(content).Replace("-", string.Empty);

                if (!Directory.Exists(".\\WAV"))
                {
                    Directory.CreateDirectory(".\\WAV");
                }

                System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex("52494646.{8}57415645666D742034");

                int i = 1;
                foreach (System.Text.RegularExpressions.Match match in rgx.Matches(contents))
                {
                    string lengths = match.Value.Substring(14, 2) + match.Value.Substring(12, 2) + match.Value.Substring(10, 2) + match.Value.Substring(8, 2);
                    int length = Convert.ToInt32(lengths, 16) * 2 + 16;
                    string exports = contents.Substring(match.Index, length);
                    byte[] export = StringToByteArray(exports);
                    File.WriteAllBytes(".\\WAV\\" + i + ".at3", export);

                    string path = Directory.GetCurrentDirectory();
                    if (File.Exists(path + "\\WAV\\" + i + ".at3"))
                    {
                        Process ProcessObj = new Process();
                        ProcessObj.StartInfo.FileName = "PS3at3tool.exe";
                        ProcessObj.StartInfo.Arguments = " -d \"" + path + "\\WAV\\" + i + ".at3\" \"" + path + "\\WAV\\" + i + ".wav\"";
                        ProcessObj.StartInfo.UseShellExecute = false;
                        ProcessObj.StartInfo.CreateNoWindow = true;
                        ProcessObj.Start();
                        ProcessObj.WaitForExit();
                        File.Delete(path + "\\WAV\\" + i + ".at3");
                    }
                    i++;
                }
            }
        }

        static byte[] StringToByteArray(String hex)
        {
            int NumberChars = hex.Length;
            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            return bytes;
        }

    }
}